<?php
/**
 * Created by PhpStorm.
 * User: 戎大富
 * Date: 2018/6/13
 * Time: 10:40
 */
namespace app\api\controller;
use think\Controller;
use think\Db;

class  Base extends Controller {
    protected $_error;
    protected $_header;//用户的请求头信息
    protected $otherLogin  = '您的账号已在其他设备登录';
    protected $frost = '您的账号当前已被冻结，如有问题请联系客服';
    protected $del = '您的账号已被删除';

    // 构造函数
    public function __construct(){
        // 如果配置项为空 则直接返回
        $server_phone = Db::table('up_other')->where('other_id', 4)->value('other_phone');
        $this->frost = $this->frost . $server_phone;
    }

    /**
     * 验证唯一——单点登录
     * user_id，time，salt，value
     * @return string
     */
    public  function checkAll($uid,$time,$value,$reqKey){
        if($uid == 0){
            return 111;
        }else{
            $user = Db::table('up_u_user')->where('user_id',$uid)->find();
            if($user['user_status'] == 3){ // 冻结
                return 110;
            }
            if($user['user_status'] == 2){ // 删除
                return 2111;
            }
            $token = $user['user_token'];
            $appId = "A6070308312682";
            $appkey = "9AF807B0-BE12-F521-6998-6D57B0CCE8BB";
            $myreqKey = md5($appId . 'XW' . $appkey . 'XW' . $time);
            $myvalue = md5($uid . 'XW' . $token . 'XW' . $time);
            if($myvalue != $value || $myreqKey != $reqKey){
                return 112;
            }else{
                return 111;
            }
        }
    }
    public  function killUpdate(){//$uid,$time,$value
        $today = date('Y-m-d');
        Db::table('up_goods')
            ->where('g_kill_end','<',$today)
            ->where('g_prcie_kill','>',0)
            ->where('g_status',1)
            ->update(['g_prcie_kill'=>0]);
    }
    /**
     * 云之讯发送短信
     * @param $phone
     * @param $num
     * @return mixed
     */
    public function duaxin($phone,$num){
//        header("Content-type: text/html; charset=utf-8");
        $body_json = array(
            'sid'=>'05b0c3cc6133227764acc0e1b6ea21ad',
            'token'=>'42c56907ae16aa3615c3945e72e26249',
            'appid'=>'414eed7c02e146598852492fa626204d',
            'templateid'=>'400297',
            'param'=>$num,
            'mobile'=>$phone,
            'uid'=>'',
        );
        $body = json_encode($body_json);
        $header = array(
            'Accept:application/json',
            'Content-Type:application/json;charset=utf-8',
        );
        $url = 'https://open.ucpaas.com/ol/sms/sendsms';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$body);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        curl_close($ch);
        $res = json_decode($result,true);
        return $res;
    }
    /**
     * param $tmp
     * param $name
     * param $size
     * 上传图片
     */
//    public function uploadFile($tmp,$name,$size)
    public function uploadFile()
    {
        $tmp = $_FILES['image']['tmp_name'];
        $name = $_FILES['image']['name'];
        $size = $_FILES['image']['size'];
        if($size > 1024*1024*5){
            return json_encode(['status'=>0,'msg'=>"图片不得超过5M！"]);
        }
        $imgarray = array('jpg','jpeg','png');
        $dir = $_SERVER['DOCUMENT_ROOT'];
        $url =  "http://".$_SERVER['HTTP_HOST'];
        if($tmp){
            //=======重命名=====
            $rand = date('YmdHis').rand(100000,999999);
            $exe = explode('.',$name);
            $exe = end($exe);
//            if(!in_array($exe,$imgarray)){
//                return json_encode(['status'=>0,'msg'=>'图片格式不支持']);
//            }
//            $newName = $rand . '.' .$exe;
            $newName = $rand . '.png';
            //=======================
            if(move_uploaded_file($tmp,"{$dir}/image/{$newName}")){
                $imgUrl = "{$url}/image/{$newName}";
                if($size > 1024*1024*2){
                    $this->image_png_size_add("{$dir}/image/{$newName}","{$dir}/image/{$newName}");
                }
                return json_encode(['status'=>200,'msg'=>$imgUrl]);
            }else{
                return json_encode(['status'=>0,'msg'=>'图片保存失败']);
            }
        }else{
            return json_encode(['status'=>0,'msg'=>"上传一张图！"]);
        }
    }

    /**
     * 压缩图片
     * @param $imgsrc:原图片地址（完整的图片路径）
     * @param $imgdst:压缩后的图片地址，也是完整的
     */
    function image_png_size_add($imgsrc,$imgdst){
        list($width,$height,$type)=getimagesize($imgsrc);
        switch($type){
            case 1:
                break;
            case 2:
                header('Content-Type:image/jpeg');
                $image = imagecreatefromjpeg($imgsrc);
                imagejpeg($image, $imgdst,20);
                imagedestroy($image);
                break;
            case 3:
                header('Content-Type:image/png');
                $image = imagecreatefrompng($imgsrc);
                imagejpeg($image, $imgdst,20);
                imagedestroy($image);
                break;
        }
    }

    /**
     * formatTime 时间格式化
     * @param $time 时间戳
     * @return string
     */
    public function formatTime($time) {
        $now_time = time();
        $t = $now_time - $time;
        $yea = (int) ($t / (86400 * 30 * 12));
        if ($yea >= 1) {
            return $yea.'年前';
        }
        $mon = (int) ($t / (86400 * 30));
        if ($mon >= 1) {
            return '一个月前';
        }
        $day = (int) ($t / 86400);
        if ($day >= 1) {
            return $day . '天前';
        }
        $h = (int) ($t / 3600);
        if ($h >= 1) {
            return $h . '小时前';
        }
        $min = (int)($t / 60);
        if ($min >= 1) {
            return $min . '分钟前';
        }
        return '刚刚';
    }
    /**
     * 获取uuid
     * @param string $prefix
     * @return string
     */
    public function uuid($prefix = '')
    {
        $chars = md5(uniqid(mt_rand(), true));
        $uuid  = substr($chars,0,8);
        $uuid .= substr($chars,8,4);
        $uuid .= substr($chars,12,4);
        $uuid .= substr($chars,16,4);
        $uuid .= substr($chars,20,12);
        return $prefix . $uuid;
    }
    /**
     * 获取任意长度的随机字符串
     * @param $length
     * @return string
     */
    function getRandChar($length)
    {
        $chars = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
            'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
            't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D',
            'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
            'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
        $char_txt = '';
        for ($i = 0; $i < $length; $i++) {
            $char_txt .= $chars[array_rand($chars)];
        }
        return $char_txt;
    }

    /**
     * 验证码
     * @param $length
     * @return string
     */
    function getCodeChar($length)
    {
        $chars = array(
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
        $char_txt = '';
        for ($i = 0; $i < $length; $i++) {
            $char_txt .= $chars[array_rand($chars)];
        }
        return $char_txt;
    }
    public function getAcount()
    {
        //==========base里放到===============
        $zimu = range('a','z');
        $one = rand(0,25);
        $two = rand(0,25);
        $thr = rand(0,25);
        $four = rand(0,25);
        $zimu2 = $zimu[$one].$zimu[$two].$zimu[$thr].$zimu[$four];
        $num = rand(100000,999999);
        return $zimu2.$num;
        //=========================
    }
    
    /**
     * 随机获取用户ID
     * @param int $times
     * @return string
     */
    public function getRandNum($times = 5){
        $nice = [
            '00000',
            '11111',
            '22222',
            '33333',
            '44444',
            '55555',
            '66666',
            '77777',
            '88888',
            '99999'
        ];
        $arr = range(0, 9);
        $num = '';
        for($i = 0; $i < $times; $i++){
            $num .= $arr[array_rand($arr)];
        }
        // 踢除靓号
        if(in_array($num, $nice)){
            $num = $this->getRandNum($times);
        }
        // 重复的号
        $rep = Db::table('up_u_user')->where('user_create_id', $num)->find();
        if($rep){
            $num = $this->getRandNum($times);
        }
        
        return $num;
    }
    
    public function rongyun($uid,$name,$imageurl){
        $appKey = config('rong.appKey');
        $appSecret = config('rong.appSecret');
        $uid = strval($uid);
        $body = "userId={$uid}&name={$name}&portraitUri={$imageurl}";
        $nonce = mt_rand();
        $timeStamp = time();
        $sign = sha1($appSecret.$nonce.$timeStamp);
        $header = array(
            'App-Key:'.$appKey,
            'Nonce:'.$nonce,
            'Timestamp:'.$timeStamp,
            'Signature:'.$sign,
            'Content-Type: application/x-www-form-urlencoded'
        );
        $url = 'http://api.cn.ronghub.com/user/getToken.json';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$body);
//    curl_setopt($ch, CURLOPT_SSL_VERI/FYPEER, false);
//    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        curl_close($ch);
        $res = json_decode($result,true);
        return $res;
//    var_dump($res) ;
    }

    //--------------------------------------------------融云群聊的操作------------------------------------------------
    //建群
    public function create($uids,$groupid,$name){
        $appKey = config('rong.appKey');
        $appSecret = config('rong.appSecret');
        $body = "{$uids}groupId=$groupid&groupName=$name";
        $nonce = mt_rand();
        $timeStamp = time();
        $sign = sha1($appSecret . $nonce . $timeStamp);
        $header = array(
            'App-Key:' . $appKey,
            'Nonce:' . $nonce,
            'Timestamp:' . $timeStamp,
            'Signature:' . $sign,
            'Content-Type: application/x-www-form-urlencoded'
        );
        $url = 'http://api.cn.ronghub.com/group/create.json';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
//    curl_setopt($ch, CURLOPT_SSL_VERI/FYPEER, false);
//    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        curl_close($ch);
        $res = json_decode($result, true);
        return $res;
    }
    //更新
    public function update($groupid,$name){
        $appKey = config('rong.appKey');
        $appSecret = config('rong.appSecret');
        $body = "groupId=$groupid&groupName=$name";
        $nonce = mt_rand();
        $timeStamp = time();
        $sign = sha1($appSecret . $nonce . $timeStamp);
        $header = array(
            'App-Key:' . $appKey,
            'Nonce:' . $nonce,
            'Timestamp:' . $timeStamp,
            'Signature:' . $sign,
            'Content-Type: application/x-www-form-urlencoded'
        );
        $url = 'http://api.cn.ronghub.com/group/refresh.json';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
//    curl_setopt($ch, CURLOPT_SSL_VERI/FYPEER, false);
//    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        curl_close($ch);
        $res = json_decode($result, true);
        return $res;
    }

    //加入
    /**
     * @return mixed
     */
    public function joinin($uidstr,$groupid,$name)
    {
        $appKey = config('rong.appKey');
        $appSecret = config('rong.appSecret');
        $body = "{$uidstr}groupId=$groupid&groupName=$name";
        $nonce = mt_rand();
        $timeStamp = time();
        $sign = sha1($appSecret . $nonce . $timeStamp);
        $header = array(
            'App-Key:' . $appKey,
            'Nonce:' . $nonce,
            'Timestamp:' . $timeStamp,
            'Signature:' . $sign,
            'Content-Type: application/x-www-form-urlencoded'
        );
        $url = 'http://api.cn.ronghub.com/group/join.json';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
//    curl_setopt($ch, CURLOPT_SSL_VERI/FYPEER, false);
//    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        curl_close($ch);
        $res = json_decode($result, true);
        return $res;
    }

    //退出
    public function getout($uidstr,$groupid)
    {
        $appKey = config('rong.appKey');
        $appSecret = config('rong.appSecret');
        $body = "{$uidstr}groupId=$groupid";
        $nonce = mt_rand();
        $timeStamp = time();
        $sign = sha1($appSecret . $nonce . $timeStamp);
        $header = array(
            'App-Key:' . $appKey,
            'Nonce:' . $nonce,
            'Timestamp:' . $timeStamp,
            'Signature:' . $sign,
            'Content-Type: application/x-www-form-urlencoded'
        );
        $url = 'http://api.cn.ronghub.com/group/quit.json';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
//    curl_setopt($ch, CURLOPT_SSL_VERI/FYPEER, false);
//    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        curl_close($ch);
        $res = json_decode($result, true);
        return $res;
    }
    //解散
    public function kill($uid,$groupid)
    {
        $appKey = config('rong.appKey');
        $appSecret = config('rong.appSecret');
        $body = "userId=$uid&groupId=$groupid";
        $nonce = mt_rand();
        $timeStamp = time();
        $sign = sha1($appSecret . $nonce . $timeStamp);
        $header = array(
            'App-Key:' . $appKey,
            'Nonce:' . $nonce,
            'Timestamp:' . $timeStamp,
            'Signature:' . $sign,
            'Content-Type: application/x-www-form-urlencoded'
        );
        $url = 'http://api.cn.ronghub.com/group/dismiss.json';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
//    curl_setopt($ch, CURLOPT_SSL_VERI/FYPEER, false);
//    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        curl_close($ch);
        $res = json_decode($result, true);
        return $res;
    }
    //---------------------------mabao--------------------------------
    
    /**
     * 请求接口返回内容
     * @param  string $url [请求的URL地址]
     * @param  string $params [请求的参数]
     * @param  int $ipost [是否采用POST形式]
     * @return  string
     */
    function juhecurl($url,$params=false,$ispost=0){
        $httpInfo = array();
        $ch = curl_init();
        
        curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
        curl_setopt( $ch, CURLOPT_USERAGENT , 'JuheData' );
        curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 60 );
        curl_setopt( $ch, CURLOPT_TIMEOUT , 60);
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        if( $ispost )
        {
            curl_setopt( $ch , CURLOPT_POST , true );
            curl_setopt( $ch , CURLOPT_POSTFIELDS , $params );
            curl_setopt( $ch , CURLOPT_URL , $url );
        }
        else
        {
            if($params){
                curl_setopt( $ch , CURLOPT_URL , $url.'?'.$params );
            }else{
                curl_setopt( $ch , CURLOPT_URL , $url);
            }
        }
        $response = curl_exec( $ch );
        if ($response === FALSE) {
            //echo "cURL Error: " . curl_error($ch);
            return false;
        }
        $httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );
        $httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );
        curl_close( $ch );
        return $response;
    }
    
    /**
     * 生成二维码
     * @param $user_id      用户ID
     * @param $match_id      赛事ID
     * @param $type         1 报到   2 签到
     * @param $url        路径 例如'http://www.baidu.com'，则直接打开百度，这里为资源路径，与phone组合成二维码内容
     * @param string $errorCorrectionLevel     容错级别L(QR_ECLEVEL_L，7%)、M(QR_ECLEVEL_M，15%)、Q(QR_ECLEVEL_Q，25%)、H(QR_ECLEVEL_H，30%)
     * @param int $matrixPointSize    生成的二维码的大小
     * @param int $margin            是否留白边
     * @return string
     */
    public function getQrcode($user_id, $match_id, $type, $url = ROOT_PATH, $errorCorrectionLevel = 'M', $matrixPointSize = 4, $margin = 2){
        import('org.phpqrcode', EXTEND_PATH, '.php');
        // 二维码内容 ROOT_PATH资源路径，
//        $value = 'user_id=' . $user_id . '&match_id=' . $match_id . '&type=' . $type;
        $value = '{user_id:' . $user_id . ',match_id:' . $match_id . ',type:' . $type . '}';
        // 创建二维码保存的文件夹
        $dir = $url . 'public' . DS . 'uploads/userQrcode';
        
        if(!file_exists($dir)){
            mkdir($dir, 0700, true);
        }
        // 后缀
        $ext = '.png';
        // 二维码资源路径
        $outfile = $dir . DS . $user_id . '_' . $match_id . '_' . date('YmdHis') . $ext;
        // 二维码访问路径
        $callfile = 'http://' . $_SERVER['HTTP_HOST'] . '/uploads/userQrcode/' . $user_id . '_' . $match_id . '_' . date('YmdHis') . $ext;
        \QRcode :: png ($value, $outfile, $errorCorrectionLevel, $matrixPointSize, $margin);
        return $callfile;
    }
    
    /**
     * 生成支付二维码
     * @param $content      二维码的支付信息
     * @param $user_id      用户ID
     * @param $order_num      订单编号
     * @param $url        路径 例如'http://www.baidu.com'，则直接打开百度，这里为资源路径，与phone组合成二维码内容
     * @param string $errorCorrectionLevel     容错级别L(QR_ECLEVEL_L，7%)、M(QR_ECLEVEL_M，15%)、Q(QR_ECLEVEL_Q，25%)、H(QR_ECLEVEL_H，30%)
     * @param int $matrixPointSize    生成的二维码的大小
     * @param int $margin            是否留白边
     * @return string
     */
    public function otherPayQrcode($content, $user_id, $order_num, $url = ROOT_PATH, $errorCorrectionLevel = 'M', $matrixPointSize = 4, $margin = 2){
        import('org.phpqrcode', EXTEND_PATH, '.php');
        // 二维码内容 ROOT_PATH资源路径，
        $value = $content;
        // 创建二维码保存的文件夹
        $dir = $url . 'public' . DS . 'uploads/otherPayQrcode';
        if(!file_exists($dir)){
            mkdir($dir, 0700, true);
        }
        // 后缀
        $ext = '.png';
        // 二维码资源路径
        $outfile = $dir . DS . $user_id . '_' . $order_num . '_' . date('YmdHis') . $ext;
        // 二维码访问路径
        $callfile = 'http://' . $_SERVER['HTTP_HOST'] . '/uploads/otherPayQrcode/' . $user_id . '_' . $order_num . '_' . date('YmdHis') . $ext;
        \QRcode :: png ($value, $outfile, $errorCorrectionLevel, $matrixPointSize, $margin);
        return $callfile;
    }
    
    
    //***************************************   支付宝当面付   start
    // 支付宝扫码支付配置信息
    protected $config_ali = array(
        'appid' => '2021001162653764',
        'ali_public' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnM8TA9p3CmsjvYQmHViw6n7QPnlp0SwUkJNgPGRW6O96YugUDtNUuEmG6pDvwNchMRXKTdCig8/UgiWK55Vej7aXf/VS9H1H2LMDB4wAZm768xss+NQdbiQGF/kMkqJT0AUlh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S7LtCNoks9/2YbP3j2MjKmhXgaOG6YHxjxZ+UARlV4mVk+qZbPNsYQxJ1gAR',
        'notify_url' => 'http://test.xuanwumobile.com/api/Ali/huidiao'
    );
    
    /**
     * 支付宝----当面付
     * @param string $no   订单号
     * @param string $money    订单金额
     * @return \think\response\Json
     */
    public function aliOtherPay($no, $money){
        header("Content-type: text/html; charset=utf-8");
        import('aliqrcode.f2fpay.model.builder.AlipayTradePrecreateContentBuilder', EXTEND_PATH, '.php');
        import('aliqrcode.f2fpay.service.AlipayTradeService', EXTEND_PATH, '.php');
        // 订单号
        $outTradeNo = $no;
        // (必填) 订单标题，粗略描述用户的支付目的。如“xxx品牌xxx门店当面付扫码消费”
        $subject = '赛事报名';
        // (必填) 订单总金额，单位为元，不能超过1亿元
        // 如果同时传入了【打折金额】,【不可打折金额】,【订单总金额】三者,则必须满足如下条件:【订单总金额】=【打折金额】+【不可打折金额】
        $totalAmount = $money;
//        $totalAmount = 0.01;
        // 订单描述，可以对交易或商品进行一个详细地描述，比如填写"购买商品2件共15.00元"
        $body = "赛事报名费用";
        // 支付超时，线下扫码交易定义为5分钟
        $timeExpress = "5m";
        // 创建请求builder，设置请求参数
        $qrPayRequestBuilder = new \AlipayTradePrecreateContentBuilder();
        $qrPayRequestBuilder->setOutTradeNo($outTradeNo);
        $qrPayRequestBuilder->setTotalAmount($totalAmount);
        $qrPayRequestBuilder->setTimeExpress($timeExpress);
        $qrPayRequestBuilder->setSubject($subject);
        $qrPayRequestBuilder->setBody($body);
        // 调用qrPay方法获取当面付应答
        $alipay_config = array(
            'gatewayUrl' => 'https://openapi.alipay.com/gateway.do',
            'app_id' => $this->config_ali['appid'],
            'sign_type' => 'RSA2',
            'merchant_private_key' => $this->config_ali['private_key'],
            'alipay_public_key' => $this->config_ali['ali_public'],
            'charset' => 'UTF-8',
            'MaxQueryRetry' => "5",
            'QueryDuration' => '5',
            'notify_url' => $this->config_ali['notify_url']
        );
        $qrPay = new \AlipayTradeService($alipay_config);
        $qrPayResult = $qrPay->qrPay($qrPayRequestBuilder);
        if ($qrPayResult->getTradeStatus() == 'SUCCESS'){
            $response = $qrPayResult->getResponse();
            $qrcode = $response->qr_code; // 返回二维码链接地址
//            $qrcode_img = $qrPay->create_erweima($qrcode); // 直接生成二维码
            $result['msg'] = $qrcode;
            $result['status'] = 200;
        }else{
            $result['msg'] = '生成二维码图片失败';
            $result['status'] = 0;
        }
        return $result;
    }
    //***************************************   支付宝当面付   end
    
    //***************************************   微信当面付     start
    // 微信扫码支付配置信息
    protected $config_wx = array(
        'APPID'              => 'wx9feafce4eccb4728', // 微信支付APPID.
        'MCHID'              => '1582362791', // 微信支付MCHID 商户收款账号  1556016481
        'KEY'                => 'NwyWVrJJX35zMM8nB2PaYPaoMVNssdH3', // 微信支付KEY
        'NOTIFY_URL'         => 'http://test.xuanwumobile.com/api/Weixin/huidiao', // 接收支付状态的连接
    );
    
    /**
     * 微信----当面付
     * @param $order   订单号
     * @param bool $type
     * @return mixed
     */
    public function WeChatPayReady($no, $money){
        $data = [
            'body' => '赛事报名', // 描述
            'total_fee' => $money * 100, //金额
//            'total_fee' => 1,
            'out_trade_no' => $no, // 订单编号
            'trade_type' => 'NATIVE', // 类型
            'product_id' =>  $no . 'abacadaeafahaj',//trade_type=NATIVE时，此参数必传。商户自行定义 32位,且同一订单必须相同
            'appid' => $this->config_wx['APPID'],
            'mch_id' => $this->config_wx['MCHID'],
            'nonce_str' => 'test',
            'spbill_create_ip' => $_SERVER['REMOTE_ADDR'],
            'notify_url' => $this->config_wx['NOTIFY_URL']
        ];
        
        // 生成签名
        $sign=$this->makeSignQ($data);
        $data['sign']=$sign;
        $xml=$this->toXmlQ($data);
        $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';//接收xml数据的文件
        $header[] = "Content-type: text/xml";//定义content-type为xml,注意是数组
        $ch = curl_init ($url);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);//严格校验
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        $response = curl_exec($ch);
        if(curl_errno($ch)){
            print curl_error($ch);
        }
        curl_close($ch);
        $result=$this->toArrayQ($response);
        if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
            $return['msg'] = $result['code_url'];
            $return['status'] = 200;
        }else{
            $return['msg'] = $result['err_code_des'];
            $return['status'] = 0;
        }
        return $return;
    }
    
    /**
     * 生成签名
     * @return 签名，本函数不覆盖sign成员变量，如要设置签名需要调用SetSign方法赋值
     */
    public function makeSignQ($data){
        // 去空
        $data = array_filter($data);
        //签名步骤一：按字典序排序参数
        ksort($data);
        $string_a = http_build_query($data);
        $string_a = urldecode($string_a);
        //签名步骤二：在string后加入KEY
        $config = $this->config_wx;
        $string_sign_temp = $string_a . "&key=" . $config['KEY'];
        //签名步骤三：MD5加密
        $sign = md5($string_sign_temp);
        // 签名步骤四：所有字符转为大写
        $result = strtoupper($sign);
        return $result;
    }
    
    /**
     * 输出xml字符
     * @throws WxPayException
     **/
    public function toXmlQ($data){
        //var_dump($data);
        if(!is_array($data) || count($data) <= 0){
            //throw new WxPayException("数组数据异常！");
        }
        $xml = "<xml>";
        foreach ($data as $key=>$val){
            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml;
    }
    
    /**
     * 将xml转为array
     * @param  string $xml xml字符串
     * @return array       转换得到的数组
     */
    public function toArrayQ($xml){
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $result= json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $result;
    }
    
    //执行第二次签名，才能返回给客户端使用
    public function getOrderQ($prepayId){
        $data["appid"] = $this->config_wx["APPID"];
        $data["noncestr"] = $this->getRandChar(32);
        $data["package"] = "Sign=WXPay";
        $data["partnerid"] = $this->config_wx['MCHID'];
        $data["prepayid"] = $prepayId;
        $data["timestamp"] = time();
        $s = $this->makeSignQ($data, false);
        $data["sign"] = $s;
        
        return $data;
    }
    
    //***************************************   微信当面付     end
    
    /**
     * 首字母
     * @param $str
     * @return string
     */
    public function zimu($str)
    {
        if(empty($str)){
            return '#';
        }
        $fchar = mb_substr($str, 0, 1, 'utf-8');
        // 判断表情    表情长度为4位
        if(strlen($fchar) >= 4 ){
            return '#';
        }
//        print_r($fchar);die;
//        $fchar=ord($str{0});
        if($fchar >= ord('A') && $fchar <= ord('z')){
            return strtoupper($str{0});
        }
        $s1 = iconv('UTF-8', 'gb2312', $str);
        $s2 = iconv('gb2312', 'UTF-8', $s1);
        $s = $s2 == $str ? $s1 : $str;
        $asc = ord($s{0})*256+ord($s{1})-65536;
        if($asc >= -20319 && $asc <= -20284) return 'A';
        if($asc >= -20283 && $asc <= -19776) return 'B';
        if($asc >= -19775 && $asc <= -19219) return 'C';
        if($asc >= -19218 && $asc <= -18711) return 'D';
        if($asc >= -18710 && $asc <= -18527) return 'E';
        if($asc >= -18526 && $asc <= -18240) return 'F';
        if($asc >= -18239 && $asc <= -17923) return 'G';
        if($asc >= -17922 && $asc <= -17418) return 'H';
        if($asc >= -17417 && $asc <= -16475) return 'J';
        if($asc >= -16474 && $asc <= -16213) return 'K';
        if($asc >= -16212 && $asc <= -15641) return 'L';
        if($asc >= -15640 && $asc <= -15166) return 'M';
        if($asc >= -15165 && $asc <= -14923) return 'N';
        if($asc >= -14922 && $asc <= -14915) return 'O';
        if($asc >= -14914 && $asc <= -14631) return 'P';
        if($asc >= -14630 && $asc <= -14150) return 'Q';
        if($asc >= -14149 && $asc <= -14091) return 'R';
        if($asc >= -14090 && $asc <= -13319) return 'S';
        if($asc >= -13318 && $asc <= -12839) return 'T';
        if($asc >= -12838 && $asc <= -12557) return 'W';
        if($asc >= -12556 && $asc <= -11848) return 'X';
        if($asc >= -11847 && $asc <= -11056) return 'Y';
        if($asc >= -11055 && $asc <= -10247) return 'Z';
        return "#";
    }
    
    /**
     * 极光推送
     * @param $type 1:推送个人  2:推送全体
     * @param $alias 别名 user_id OR token
     * @param $message 推送消息内容
     * @param $extras 扩展字段接受数组
     * @return array
     */
    public function Jpush($type,$alias,$message,$extras)
    {
//        $alias = (string)$alias;
        import('jpush.autoload', EXTEND_PATH);
        //初始化JPushClient
        $client = new \JPush\Client(config('jpush.appKey'),config('jpush.masterSecret'));
        //生成推送Payload构建器
        $push = $client->push();
        //推送平台 'all'  OR  ['ios','android']  OR  'ios','android'
        $push->setPlatform('all');
        //1:推送个人  2:推送全体
        if($type==1){
            $push->addAlias($alias);//按别名推送
        }else{
            $push->addAllAudience();//广播消息推送
        }
        //IOS推送
        $push->iosNotification($message, [
                'alert'=>$message,
                'badge' => '+1',
                'extras' => $extras,
                'sound'=>'default'
            ]
        );
        //Android推送
        $push->androidNotification($message, [
                'alert'=>$message,
                'extras' => $extras
            ]
        );
        $push->message($message, [
//            'title' => 'Hello',
            'content_type' => 'text',
            'extras' => $extras
        ]);
        return $push->send();
    }
    
    /**
     * 极光推送--推送消息类型
     * @param $type 1:推送个人  2:推送全体
     * @param $alias 别名 user_id OR token
     * @param $message 推送消息内容
     * @param $code
     * @return array
     */
    public function Jpush1($type,$alias,$message,$code)
    {
//        $alias = (string)$alias;
        import('jpush.autoload', EXTEND_PATH);
        //初始化JPushClient
        $client = new \JPush\Client(config('jpush.appKey'),config('jpush.masterSecret'));
        //生成推送Payload构建器
        $push = $client->push();
        //推送平台 'all'  OR  ['ios','android']  OR  'ios','android'
        $push->setPlatform('all');
        //1:推送个人  2:推送全体
        if($type==1){
            $push->addAlias($alias);//按别名推送
        }else{
            $push->addAllAudience();//广播消息推送
        }
        $push->message($message, [
//            'title' => 'Hello',
            'content_type' => 'text',
            'extras' => [
                'key' => $code
            ]
        ]);
        return $push->send();
    }
    
    function getAge($birthday){
        $time = strtotime($birthday);//取得生日的时间戳
        $byear = date('Y', $time);//生日时间--年
        $bmonth = date('m', $time);//生日时间--月
        $bday = date('d', $time);//生日时间--日
        //初始化当前日期
        $nyear = date('Y');
        $nmonth = date('m');
        $nday = date('d');
        //计算年龄
        $age = $nyear - $byear;
        //如果当前时间的month小于生日的month，则年龄-1岁
        if($nmonth < $bmonth){
            $age = $age - 1;
            //如果当前时间的month等于生日的month，并且当前时间的day小于生日的day，则年龄-1
        }elseif($nmonth == $bmonth && $nday < $bday){
            $age = $age - 1;
        }
        return $age;
    }
}